﻿using Clancy.Interfaces;
using System;
using System.ServiceModel;

namespace Clancy.Service.Base
{
    internal class ServiceController : IServiceController
    {
        private readonly IRecordingManager m_RecordingManager;
        private readonly ISurveilanceLogic m_SurveilanceLogic;
        private readonly ISurveilanceStorage m_SurveilanceStorage;
        private readonly IVideoSourceProvider m_VideoSourceProvider;
        private ServiceHost m_ClancyServiceHost;
        private ServiceHost m_LiveStreamHost;
        private ClancyCommunicationService m_SingeltonClancyCommunicationService;
        private LiveStreamFeedbackService m_SingeltonLiveStreamFeedbackService;

        public ServiceController(ISurveilanceLogic surveilanceLogic, ISurveilanceStorage surveilanceStorage, IVideoSourceProvider videoSourceProvider, IRecordingManager recordingManager)
        {
            m_SurveilanceLogic = surveilanceLogic;
            m_SurveilanceStorage = surveilanceStorage;
            m_VideoSourceProvider = videoSourceProvider;
            m_RecordingManager = recordingManager;
        }

        public void CloseCommunicationService()
        {
            if (m_ClancyServiceHost != null)
            {
                try
                {
                    m_ClancyServiceHost.Close();
                }
                catch
                {
                }
                m_ClancyServiceHost = null;
            }

            if (m_LiveStreamHost != null)
            {
                try
                {
                    m_LiveStreamHost.Close();
                }
                catch
                {
                }
                m_LiveStreamHost = null;
            }
        }

        public void Dispose()
        {
            CloseCommunicationService();

            m_SingeltonLiveStreamFeedbackService.Dispose();
        }

        public void OpenCommunicationService(string ipAddress, int port)
        {
            m_SingeltonClancyCommunicationService = new ClancyCommunicationService(m_SurveilanceLogic, m_SurveilanceStorage, m_VideoSourceProvider);
            m_ClancyServiceHost = new ServiceHost(m_SingeltonClancyCommunicationService);
            m_ClancyServiceHost.Open();

            m_SingeltonLiveStreamFeedbackService = new LiveStreamFeedbackService(m_SurveilanceLogic, m_SurveilanceStorage, m_RecordingManager);
            m_LiveStreamHost = new ServiceHost(m_SingeltonLiveStreamFeedbackService);
            m_LiveStreamHost.Open();
        }

        public void StartSurveilance()
        {
            m_SurveilanceLogic.Start();
        }

        public void StopSurveilance()
        {
            m_SurveilanceLogic.Stop();
        }
    }
}